package com.mao.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mao.entity.Employee;
import com.mao.mapper.EmployeeMapper;
import com.mao.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Service
@Slf4j
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {

    @Override
    public Employee login(HttpServletRequest request, Employee employee) {
        //1.对密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2.检查用户名是否存在数据库
        LambdaQueryWrapper<Employee> lq=new LambdaQueryWrapper<>();
        lq.eq(Employee::getUsername,employee.getUsername());
        Employee data = this.getOne(lq);

        //5.所有校验通过，跳转到登录页面，并将用户ID保存到session
        request.getSession().setAttribute("employee",data.getId());
        return data;
    }

    @Override
    public String save(HttpServletRequest request, Employee employee) {
        //1.给员工初始密码123456
        employee.setPassword(DigestUtils.md5DigestAsHex(("123456").getBytes()));
        //2.设置创建和更新的时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //3.设置当前操作的员工的id
        Long eid = (Long) request.getSession().getAttribute("employee");
        employee.setCreateUser(eid);
        employee.setUpdateUser(eid);
        //4.最后保存新员工
        boolean isTF = this.save(employee);
        if (!isTF){
            return "新增失败";
        }
        return "新增成功";
    }

    @Override
    public Page<Employee> page(int page, int pageSize, String name) {
        //1.创建分页构造器
        Page<Employee> pageInfo = new Page(page,pageSize);
        //2.创建条件查询构造器
        LambdaQueryWrapper<Employee> lqw=new LambdaQueryWrapper<>();
        //3.添加过滤的条件
        lqw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        //4.添加排序规则
        lqw.orderByDesc(Employee::getUpdateTime);
        //5.执行查询
        this.page(pageInfo,lqw);
        //6.返回处理后的分页构造器
        return pageInfo;
    }

    @Override
    public String updateEmployee(HttpServletRequest request, Employee employee) {
        //1.修改更新时间
        employee.setUpdateTime(LocalDateTime.now());
        //2.修改做更新操作的用户
        Long o = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(o);
        boolean isTF = this.updateById(employee);
        if (!isTF){
            return "修改失败";
        }
        return "修改成功";
    }
}
